package com.szml.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LogAspect {

    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    // 定义切点表达式，这里我们拦截所有Service层的方法
    @Pointcut("execution(* com.szml.service..*.*(..))")
    public void serviceLog() {}

    // 在方法执行之前执行
    @Before("serviceLog()")
    public void beforeService(JoinPoint joinPoint) {
        // 获取方法名称和参数
        String methodName = joinPoint.getSignature().toShortString();
        Object[] args = joinPoint.getArgs();

        logger.info("在方法执行之前：方法名: {}, 参数列表: {}", methodName, args);
    }

    // 在方法正常返回之后执行
    @AfterReturning(pointcut = "serviceLog()", returning = "result")
    public void afterReturningService(JoinPoint joinPoint, Object result) {
        String methodName = joinPoint.getSignature().toShortString();

        logger.info("方法正常返回 method: {}, with result: {}", methodName, result);
    }

    // 在方法抛出异常后执行
    @AfterThrowing(pointcut = "serviceLog()", throwing = "e")
    public void afterThrowingService(JoinPoint joinPoint, Throwable e) {
        String methodName = joinPoint.getSignature().toShortString();

        logger.warn("方法抛出异常: {}, with exception: {}", methodName, e.getMessage());
    }

    // 在方法执行之后执行（无论是否抛出异常）
    @After("serviceLog()")
    public void afterService(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().toShortString();

        logger.info("方法执行之后：method: {}", methodName);
    }
}

